<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新建角色
          </el-button>
        </div>
      </template>

      <!-- 角色列表 -->
      <el-table :data="roleList" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="roleCode" label="角色编码" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="380" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editRole(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="assignPermissions(scope.row)">
              分配权限
            </el-button>
            <el-button size="small" type="success" @click="assignMenus(scope.row)">
              分配菜单
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleRoleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteRole(scope.row)"
              :disabled="scope.row.roleCode === 'SUPER_ADMIN'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog 
      v-model="roleDialogVisible" 
      :title="isEdit ? '编辑角色' : '新建角色'"
      width="500px"
    >
      <el-form 
        ref="roleFormRef" 
        :model="roleForm" 
        :rules="roleRules" 
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="roleForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog 
      v-model="permissionDialogVisible" 
      title="分配权限"
      width="600px"
    >
      <div class="permission-tree">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="permissionTreeProps"
          show-checkbox
          node-key="id"
          default-expand-all
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 菜单分配对话框 -->
    <el-dialog 
      v-model="menuDialogVisible" 
      title="分配菜单"
      width="600px"
    >
      <div class="menu-tree">
        <el-tree
          ref="menuTreeRef"
          :data="menuTree"
          :props="menuTreeProps"
          show-checkbox
          node-key="id"
          default-expand-all
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="menuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMenus">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {userApi, permissionApi, menuApi, roleApi} from "../api/index";

// 响应式数据
const loading = ref(false)
const roleList = ref([])
const roleDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const menuDialogVisible = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)

// 角色表单
const roleFormRef = ref()
const roleForm = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 权限树
const permissionTree = ref([])
const permissionTreeRef = ref()
const permissionTreeProps = {
  children: 'children',
  label: 'permissionName'
}

// 菜单树
const menuTree = ref([])
const menuTreeRef = ref()
const menuTreeProps = {
  children: 'children',
  label: 'menuName'
}

// 生命周期
onMounted(() => {
  loadRoleList()
  loadPermissionTree()
  loadMenuTree()
})

// 加载角色列表
const loadRoleList = async () => {
  try {
    loading.value = true
    const response = await roleApi.getRoleList()
    if (response.data.code === 200) {
      roleList.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('加载角色列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载权限树
const loadPermissionTree = async () => {
  try {
    const response = await permissionApi.getPermissionList()
    if (response.data.code === 200) {
      permissionTree.value = buildTree(response.data.data)
    }
  } catch (error) {
    ElMessage.error('加载权限树失败')
    console.error(error)
  }
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    const response = await menuApi.getMenuTree()
    if (response.data.code === 200) {
      menuTree.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('加载菜单树失败')
    console.error(error)
  }
}

// 构建树形结构
const buildTree = (data, parentId = null) => {
  return data
    .filter(item => item.parentId === parentId)
    .map(item => ({
      ...item,
      children: buildTree(data, item.id)
    }))
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  resetRoleForm()
  roleDialogVisible.value = true
}

// 编辑角色
const editRole = (role) => {
  isEdit.value = true
  Object.assign(roleForm, role)
  roleDialogVisible.value = true
}

// 重置角色表单
const resetRoleForm = () => {
  roleForm.id = null
  roleForm.roleName = ''
  roleForm.roleCode = ''
  roleForm.description = ''
  roleForm.sort = 0
  roleForm.status = 1
  roleFormRef.value?.resetFields()
}

// 保存角色
const saveRole = async () => {
  try {
    await roleFormRef.value.validate()
    
    if (isEdit.value) {
      const response = await roleApi.updateRole(roleForm.id, roleForm)
      if (response.data.code === 200) {
        ElMessage.success('角色更新成功')
        roleDialogVisible.value = false
        loadRoleList()
      }
    } else {
      const response = await roleApi.createRole(roleForm)
      if (response.data.code === 200) {
        ElMessage.success('角色创建成功')
        roleDialogVisible.value = false
        loadRoleList()
      }
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
    console.error(error)
  }
}

// 删除角色
const deleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${role.roleName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.deleteRole(role.id)
    if (response.data.code === 200) {
      ElMessage.success('角色删除成功')
      loadRoleList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 切换角色状态
const toggleRoleStatus = async (role) => {
  try {
    const newStatus = role.status === 1 ? 0 : 1
    const response = await roleApi.updateRoleStatus(role.id, newStatus)
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      loadRoleList()
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error(error)
  }
}

// 分配权限
const assignPermissions = async (role) => {
  currentRole.value = role
  try {
    const response = await roleApi.getRoleById(role.id)
    if (response.data.code === 200) {
      const permissionIds = response.data.data.map(p => p.id)
      permissionTreeRef.value.setCheckedKeys(permissionIds)
    }
  } catch (error) {
    console.error(error)
  }
  permissionDialogVisible.value = true
}

// 保存权限分配
const savePermissions = async () => {
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const response = await roleApi.assignPermissionsToRole(currentRole.value.id, checkedKeys)
    if (response.data.code === 200) {
      ElMessage.success('权限分配成功')
      permissionDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('权限分配失败')
    console.error(error)
  }
}

// 分配菜单
const assignMenus = async (role) => {
  currentRole.value = role
  try {
    const response = await  roleApi.getRoleById(role.id)
    if (response.data.code === 200) {
      const menuIds = response.data.data.map(m => m.id)
      menuTreeRef.value.setCheckedKeys(menuIds)
    }
  } catch (error) {
    console.error(error)
  }
  menuDialogVisible.value = true
}

// 保存菜单分配
const saveMenus = async () => {
  try {
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    const response = await roleApi.assignMenusToRole(currentRole.value.id, checkedKeys)
    if (response.data.code === 200) {
      ElMessage.success('菜单分配成功')
      menuDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('菜单分配失败')
    console.error(error)
  }
}
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-tree,
.menu-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
